﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;

public class bletest : MonoBehaviour
{
	//public GameObject receiveObject;
	// Use this for initialization
	public Text text,VectorText,powerText;
	private int callIndex = 0;
	public Text CallIndexText;
	public Quaternion m_RotationNow;
	private Quaternion fixRotation;
    public ParserMahony parserMahony ;
    public List<Dropdown> m_Options = new List<Dropdown>();
    public List<Toggle> m_ToggleList = new List<Toggle>();
    public DateTime m_lastTime, m_nowTime;
    public bool m_IsPushed;
    public Image m_X, m_Y, m_Z,m_X1,m_Y1,m_Z1;
    private Vector3 m_gyro;
    private bool m_lastPushed;
    private float m_timeCount;
    //string filename = "/sdcard/data/SensorData";
    StreamWriter sw ;

    MadgwickAHRS ahrs ;
    MahonyAHRS mahony;
    List<int> list = new List<int>();
    void Start()
	{
        //print(DateTime.Now.ToFileTimeUtc());
        //sw = new StreamWriter(Application.persistentDataPath + "/data.txt",false);
        //sw.AutoFlush = true;
        scan();
        //string s = "1,1,1,1,1,1,1,1,1";
        //onReceivse(s);
        //string s1 = "0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5";
        //onReceivse(s1);
        //ahrs = new MadgwickAHRS(0.05f,0.05f);
        //mahony = new MahonyAHRS();
        //mahony.Mahony_Init();
        //parserMahony = new ParserMahony();
        //parserMahony.Init();
    }
    public AndroidJavaObject GetFromUnityObj() {
		try
		{
			AndroidJavaClass jc = new AndroidJavaClass("com.seventh.blekit.FromUnity");
			AndroidJavaObject androidObj = jc.CallStatic<AndroidJavaObject>("getInstance");
			//Debug.Log("正常");
			return androidObj;
		}
		catch (System.Exception ex)
		{
			Debug.Log(ex.ToString());
			throw ex;
		}
	}
	public void Reset()//重置角度
    {
		fixRotation = m_RotationNow;
    }
    public void scan()
    {
		try
		{
			AndroidJavaObject obj = GetFromUnityObj();
            obj.Call("setGameObjectName", "receiveObject");
            obj.Call("setFunctionName", "onReceivse");

			obj.Call("scan");
			//getFromUnityObj().Call("disconnect");
			Debug.Log("正常");
		}
		catch (System.Exception ex)
		{
			Debug.Log(ex.ToString());
		}
	}

	public void DisConnect()
	{
		try
		{
			AndroidJavaObject obj = GetFromUnityObj();
			//obj.Call("setGameObjectName", "`");
			//obj.Call("setFunctionName", "onReceivse");

            //obj.Call("scan");
            obj.Call("disconnect");

            //getFromUnityObj().Call("disconnect");
            Debug.Log("正常");
		}
		catch (System.Exception ex)
		{
			Debug.Log(ex.ToString());
		}
	}
	// Update is called once per frame
	private float _time = 1;
    void Update() {
        _time -= Time.deltaTime;
        if (_time < 0) {
            CallIndexText.text = callIndex.ToString();
            _time = 0.5f;
            callIndex = 0;
        }
        //string s = "0.1,0.2,0.3,0.4,0,0,0";
        //onReceivse(s);
        if (!m_lastPushed && m_IsPushed) {
            Reset();
        }
        m_lastPushed = m_IsPushed;
        if (m_gyro.x > 0) {
            m_X.fillAmount = m_gyro.x / 360f;
            m_X1.fillAmount = 0;
        } else {
            m_X1.fillAmount = -m_gyro.x / 360f;
            m_X.fillAmount = 0;
        }
        if (m_gyro.y > 0) {
            m_Y.fillAmount = m_gyro.y / 360f;
            m_Y1.fillAmount = 0;
        } else {
            m_Y1.fillAmount = -m_gyro.y / 360f;
            m_Y.fillAmount = 0;
        }
        if (m_gyro.z > 0) {
            m_Z.fillAmount = m_gyro.z / 360f;
            m_Z1.fillAmount = 0;
        } else {
            m_Z1.fillAmount =- m_gyro.z / 360f;
            m_Z.fillAmount = 0;
        }

    }


        void onReceivse(string data)//Android原生调用，接收蓝牙数据，数据格式如下： q0-q3为四元数原始值，gx-gz为陀螺仪角速度，ax-az为加速度计三轴加速度值，buttonflag为1为按键按下，否则为0，power为电量
                                    //数据格式：q0,q1,q2,q3,gx,gy,gz,ax,ay,az,buttonflag,power，以逗号分隔
    {
        //Debug.Log(data);
        //m_nowTime = DateTime.Now;

        //TimeSpan ts1 = new TimeSpan(m_nowTime.Ticks);
        //TimeSpan ts2 = new TimeSpan(m_lastTime.Ticks);
        //TimeSpan tsSub = ts1.Subtract(ts2).Duration();
        //m_lastTime = m_nowTime;
        //m_timeCount += tsSub.Milliseconds;
        //print(tsSub.Milliseconds);

		string _da = data;
		var _d = _da.Split(',');
        List<float> qlist = new List<float>();
        if(int.Parse(_d[10]) == 1) {
            m_IsPushed = true;
        } else {
            m_IsPushed = false;
        }
        powerText.text = float.Parse(_d[11]).ToString();
        //qlist.Add(0);
        //qlist.Add(0);
        //qlist.Add(0);
        //qlist.Add(0);

        //qlist[m_Options[0].value] = float.Parse(_d[0]);
        //qlist[m_Options[1].value] = float.Parse(_d[1]);
        //qlist[m_Options[2].value] = float.Parse(_d[2]);
        //qlist[m_Options[3].value] = float.Parse(_d[3]);

        float a, b, c, d;
        if (m_ToggleList[0].isOn) {
            a = 1f;
        } else {
            a = -1f;
        }
        if (m_ToggleList[1].isOn) {
            b = 1f;
        } else {
            b = -1f;
        }
        if (m_ToggleList[2].isOn) {
            c = 1f;
        } else {
            c = -1f;
        }
        if (m_ToggleList[3].isOn) {
            d = 1f;
        } else {
            d = -1f;
        }
        
        Quaternion q = new Quaternion();
        //q = new Quaternion(a*qlist[0], b*qlist[1], c*qlist[2], d*qlist[3]);
        q = new Quaternion(float.Parse(_d[1]),- float.Parse(_d[3]),float.Parse(_d[2]),float.Parse(_d[0]));//四元数原始值做矩阵变换，适应unity坐标系

        //Vector3 v3 = new Vector3(float.Parse(_d[4])/10f,float.Parse(_d[5])/10f,float.Parse(_d[6])/10f);
        //gameObject.GetComponent<Rigidbody>().angularVelocity = v3;
        gameObject.transform.eulerAngles = q.eulerAngles - fixRotation.eulerAngles;//修复坐标
        m_RotationNow = q;//保留当前数据，做修复用
        text.text = gameObject.transform.eulerAngles.ToString("#0.00");
        Vector3 gyro = new Vector3(float.Parse(_d[4]), float.Parse(_d[5]), float.Parse(_d[6]));
        m_gyro = gyro;
        VectorText.text = gyro.ToString("#0.00");
        callIndex++;
        //long time = DateTime.Now.ToBinary();
        //sw.WriteLine(m_timeCount.ToString()+","+ gameObject.transform.rotation .eulerAngles.y+ "\r\n");

    }
    private void OnApplicationQuit() {
        sw.Close();
    }
}

